#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <fcntl.h>
using namespace std;
const string gpipefile = "./fifo";
const mode_t gfifomode = 0600;
const int gdefultfd = -1;
const int gfifosize = 1024;
const int gForRead = O_RDONLY;
const int gForWrite = O_WRONLY;

class Fifo
{
private:
    int Openfifo(int flag)
    {
        // 如果读端打开文件时,写端还没有打开,读端就会对用的open就会阻塞
        _fd = ::open(gpipefile.c_str(), flag);
        if (_fd < 0)
        {
            cerr << "open error" << endl;
        }
        return _fd;
    }

public:
    Fifo() : _fd(-1)
    {
        int n = mkfifo(gpipefile.c_str(), gfifomode);
        if (n < 0)
        {
            //cout << "mkfifo error" << endl;
            return;
        }
        cout << "mkfifo success " << endl;
    }
    bool OpenfifoWrite()
    {
        _fd = Openfifo(gForWrite);
        if (_fd < 0)
            return false;
        return true;
    }
    bool OpenfifoRead()
    {
        _fd = Openfifo(gForRead);
        if (_fd < 0)
            return false;
        return true;
    }

    int wait()
    {
        int code = 0;
        ssize_t rd = read(_fd, &code, sizeof(code));
        if (rd == sizeof(code))
        {
            return 0;
        }
        else if (rd == 0)
        {
            return 1;
        }
        else
        {
            return 2;
        }
    }

    int Sendfifo()
    {
        int code = 1;
        return write(_fd, &code, sizeof(code));
    }

    ~Fifo()
    {
        if (_fd >= 0)
            ::close(_fd);

        int n = unlink(gpipefile.c_str()); // 关闭fifo
        if (n < 0)
        {
            cout << "unlink error" << endl;
            return;
        }
        cout << "unlink success " << endl;
    }

private:
    int _fd;
};

Fifo fifo;